import { getCaptcha, checkCode, userLogin, checkLoginName } from '@/services/login/index';
import { getSystemInfo } from '@/services/main/index';
import React, { useState, useEffect } from 'react';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { history, SelectLang, useIntl, useModel } from '@umijs/max';
import CryptoJS from 'crypto-js';
import { Form, Input, Button, Modal, Image, message } from 'antd';
import { clearSessionToken, setSessionToken } from '@/access';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import styles from './index.less';
import loginBg from './images/login-avigation.png';

const iv =  CryptoJS.enc.Utf8.parse("2020070221160001");
const key = CryptoJS.enc.Utf8.parse('2020070221160001');
const aesEncryptWithMode = (param)=>{
    var source = CryptoJS.enc.Utf8.parse(param);
    var target = CryptoJS.AES.encrypt(param, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding:CryptoJS.pad.Pkcs7

    });
    return target.ciphertext.toString().toUpperCase();
}


const Lang = () => {
    const langClassName = useEmotionCss(({ token }) => {
      return {
        width: 42,
        height: 42,
        lineHeight: '42px',
        position: 'fixed',
        right: 16,
        borderRadius: token.borderRadius,
        ':hover': {
          backgroundColor: token.colorBgTextHover,
        },
      };
    });
  
    return (
      <div className={langClassName} data-lang>
        {SelectLang && <SelectLang />}
      </div>
    );
  };

const Login: React.FC = () => {
  const { refresh } = useModel('@@initialState');
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({code: 200});
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [captchaImage, setCaptchaImage] = useState<string>('');
  const [enableCode, setEnableCode] = useState<boolean>(false); // 从系统配置获取

  const intl = useIntl();

  useEffect(() => {
    // 初始化验证码
    if(enableCode){
        refreshCaptcha();
    }
  }, []);

  const refreshCaptcha = async (): Promise<void> => {
    const blob = await getCaptcha();
    const url = URL.createObjectURL(blob);
    setCaptchaImage(url);
  };
  
  const handleSubmit = async (values: API.LoginParams): Promise<void> => {
    setLoading(true);
    try {
      // 验证验证码
        if (enableCode) {
        const codeValid = await checkCode({ curCode: values.kaptcha,kaptcha:values.kaptcha });
        if (!codeValid) {
          const defaultMessage = intl.formatMessage({
                id: 'pages.login.phoneLogin.errorMessage',
                defaultMessage: '验证码错误！',
          });
          message.error(defaultMessage);
          setLoading(false);
          return;
        }
        }
        let params = {
            username: values.username,
            password: aesEncryptWithMode(values.password)
        }
        if(enableCode){
            params['kaptcha'] = values.kaptcha;
        }
        // 执行登录
        const response = await userLogin(params);
        // console.log("login response===>",response)
        if (response.data.code === 0) {
            const defaultLoginSuccessMessage = intl.formatMessage({
                id: 'pages.login.success',
                defaultMessage: '登录成功！',
            });
            // message.info(defaultLoginSuccessMessage);
            const current = new Date();
            const expireTime = current.setTime(current.getTime() + 1000 * 12 * 60 * 60);
            let token = response?response.headers.authorization:"";
            setSessionToken(token, token, expireTime);
            const systemInfo = await getSystemInfo();
            const initialState = {
                menuItems: systemInfo.data.menus,
                currentUser: systemInfo.data.user,
                systemConfig:systemInfo.data.systemConfig,
                permission:systemInfo.data.buttons
            };
            localStorage.setItem('menu-cache', JSON.stringify(initialState));
             const urlParams = new URL(window.location.href).searchParams;
             const redirect = urlParams.get('redirect') || '/page/main';
             // 先跳转到目标页面
             history.replace(redirect);
             // 然后刷新页面以重新加载路由
             setTimeout(() => {
                 window.location.reload();
             }, 100);
          return;
        } else {
          message.error(response.data.message);
          console.log("----用户登录失败，clearSessionToken");
          clearSessionToken();
          // 如果失败去设置用户错误信息
          setUserLoginState({ ...response });
          if (enableCode) {
            refreshCaptcha();
          }
        }
    } catch (error) {
        const defaultLoginFailureMessage = intl.formatMessage({
            id: 'pages.login.failure',
            defaultMessage: '登录失败，请重试！',
        });
        message.error(defaultLoginFailureMessage);
        if (enableCode) {
            refreshCaptcha();
        }
    } finally {
      setLoading(false);
    }
  };

  const handleForgetPassword = async (): Promise<void> => {
    try {
      const username = form.getFieldValue('username');
      const defaultMessage = intl.formatMessage({
        id: 'pages.login.username.required',
        defaultMessage: '请输入登录名',
    });
      if (!username) {
        message.warning(defaultMessage);
        return;
      }
    const response = await checkLoginName({ loginName: username });
      if (response.code === 0) {
        history.push(`/forgetPwd?userName=${username}`);
      } else {
        message.error(response.msg);
      }
    } catch (error) {
        const defaultMessage = intl.formatMessage({
            id: 'pages.login.username.validError',
            defaultMessage: '验证登录名失败',
        });
      message.error(defaultMessage);
    }
  };

  const handleBeianClick = (): void => {
    Modal.confirm({
      title: '系统提示',
      content: '是否跳转工信部网站',
      onOk: () => {
        window.open('https://beian.miit.gov.cn/#/Integrated/index');
      },
    });
  };

  return (
    <div className={styles.container}>
      <Lang />
      <div className={styles.content}>
        <div className={styles.leftPanel}>
          <div className={styles.logoPanel}>
            <Image 
              src={loginBg} 
              preview={false} 
              className={styles.logoImage} 
            />
          </div>
        </div>
        
        <div className={styles.rightPanel}>
          <Form
            form={form}
            name="login"
            className={styles.loginForm}
            initialValues={{ remember: true }}
            onFinish={handleSubmit}
            size="large"
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                form.submit();
              }
            }}
          >
            <div className={styles.top}>
                <h1 className={styles.title}>综合档案管理系统</h1>
            </div>
            <Form.Item
              name="username"
              rules={[{ required: true, message: intl.formatMessage({
                id: 'pages.login.username.required',
                defaultMessage: '请输入登录名',
              }) }]}
            >
              <Input
                prefix={<UserOutlined className={styles.prefixIcon} />}
                placeholder={intl.formatMessage({
                id: 'pages.login.username.required',
                defaultMessage: '请输入登录名',
                })}
                className={styles.uName}
              />
            </Form.Item>
            
            <Form.Item
              name="password"
              rules={[{ required: true, message: intl.formatMessage({
                id: 'pages.login.password.required',
                defaultMessage: '请输入密码',
              }) }]}
            >
              <Input.Password
                prefix={<LockOutlined className={styles.prefixIcon} />}
                placeholder={
                    intl.formatMessage({
                        id: 'pages.login.password.required',
                        defaultMessage: '请输入密码',
                    })
                }
                className={styles.uPwd}
              />
            </Form.Item>
            
            {enableCode && (
              <Form.Item
                name="kaptcha"
                rules={[
                  { required: true, message: intl.formatMessage({
                    id: 'pages.login.captcha.required',
                    defaultMessage: '验证码不能为空',
                }) },
                  {
                    validator: async (_, value) => {
                      if (value) {
                        const valid = await checkCode({ curCode: value,kaptcha:value});
                        if (!valid) {
                          throw new Error(
                            intl.formatMessage({
                                id: 'pages.login.phoneLogin.errorMessage',
                                defaultMessage: '验证码错误',
                            })
                          );
                        }
                      }
                    },
                  },
                ]}
              >
                <div className={styles.captchaContainer}>
                  <Input
                    className={styles.captchaInput}
                    placeholder={
                        intl.formatMessage({
                            id: 'pages.login.captcha.placeholder',
                            defaultMessage: '请输入验证码！',
                        })
                    }
                    maxLength={4}
                  />
                  <div 
                    className={styles.captchaImage} 
                    onClick={refreshCaptcha}
                    title={
                        intl.formatMessage({
                            id: 'pages.login.phoneLogin.getVerificationCode',
                            defaultMessage: '获取验证码',
                        })
                    }
                  >
                    <Image 
                      src={captchaImage} 
                      preview={false} 
                      width="100%"
                      height="100%"
                    />
                  </div>
                </div>
              </Form.Item>
            )}
            
            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className={styles.submitButton}
                loading={loading}
                block
              >
                {intl.formatMessage({
                    id: 'pages.login.submit',
                    defaultMessage: '登录',
                })}
              </Button>
            </Form.Item>
            
            <div className={styles.other}>
              <a onClick={handleForgetPassword}>
              {intl.formatMessage({
                    id: 'pages.login.forgotPassword',
                    defaultMessage: '忘记密码',
                })}
             </a>
            </div>
          </Form>
        </div>
        <div className={styles.footer}>
            <div className={styles.copyright}>
            Copyright &copy; 2023 银雁 | <a onClick={handleBeianClick}>粤ICP备18013953号</a>
            </div>
        </div>
      </div>
      
      
    </div>
  );
};

export default Login;